import { useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Image, Upload, Button } from 'antd';
import type { GetProp, UploadFile, UploadProps } from 'antd';
import useJwt from '../../UseJwt';

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

const getBase64 = (file: FileType): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });

const UploadFile = () => {
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as FileType);
    }

    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
  };

  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) =>
    setFileList(newFileList);

  const handleCustomRequest = () => {
    console.log('customRequest')
  }

  // 开始上传
  const handleUploadImg = () => {
    if (!fileList.length) {
      return
    }
    const file = fileList[0]
    const fd = new FormData()
    fd.append('name', file.name)
    fd.append('file', (file.originFileObj as Blob), 'file')

    useJwt.uploadFile(fd)
  }

  const uploadButton = (
    <button style={{ border: 0, background: 'none' }} type="button">
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传</div>
    </button>
  );
  return (
    <div
      className="h-screen py-[10%]"
    >
      <div
        className="shadow border w-[80%] m-auto h-[90%] rounded p-2"
      >
         <Upload
          action=""
          listType="picture-card"
          fileList={fileList}
          onPreview={handlePreview}
          onChange={handleChange}
          customRequest={handleCustomRequest}
          beforeUpload={() => false}
        >
          {fileList.length >= 1 ? null : uploadButton}
        </Upload>
        {previewImage && (
          <Image
            wrapperStyle={{ display: 'none' }}
            preview={{
              visible: previewOpen,
              onVisibleChange: (visible) => setPreviewOpen(visible),
              afterOpenChange: (visible) => !visible && setPreviewImage(''),
            }}
            src={previewImage}
          />
        )}

        <Button
          className='mt-4'
          type="primary"
          onClick={handleUploadImg}
        >
          上传图片
        </Button>
      </div>
    </div>
  )
}


export default UploadFile